package com.frp.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 配置加载器
 * 负责加载和验证FRP客户端配置
 */
public class ConfigLoader {
    private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    
    /**
     * 从文件加载配置
     */
    public static FrpcConfig loadFromFile(String filePath) throws IOException {
        return mapper.readValue(new File(filePath), FrpcConfig.class);
    }
    
    /**
     * 从字符串加载配置
     */
    public static FrpcConfig loadFromString(String content) throws IOException {
        return mapper.readValue(content, FrpcConfig.class);
    }
    
    /**
     * 验证配置
     */
    public static void validateConfig(FrpcConfig config) {
        if (config == null) {
            throw new IllegalArgumentException("配置不能为空");
        }
        
        if (config.getCommon() == null) {
            throw new IllegalArgumentException("common配置不能为空");
        }
        
        if (config.getCommon().getServerAddr() == null || config.getCommon().getServerAddr().trim().isEmpty()) {
            throw new IllegalArgumentException("服务器地址不能为空");
        }
        
        if (config.getCommon().getServerPort() <= 0 || config.getCommon().getServerPort() > 65535) {
            throw new IllegalArgumentException("服务器端口必须在1-65535之间");
        }
        
        if (config.getCommon().getToken() == null || config.getCommon().getToken().trim().isEmpty()) {
            throw new IllegalArgumentException("token不能为空");
        }
        
        if (config.getProxies() == null || config.getProxies().isEmpty()) {
            throw new IllegalArgumentException("代理配置不能为空");
        }
        
        for (FrpcConfig.ProxyConfig proxy : config.getProxies()) {
            if (proxy.getName() == null || proxy.getName().trim().isEmpty()) {
                throw new IllegalArgumentException("代理名称不能为空");
            }
            
            if (proxy.getType() == null || proxy.getType().trim().isEmpty()) {
                throw new IllegalArgumentException("代理类型不能为空");
            }
            
            if (proxy.getLocalPort() <= 0 || proxy.getLocalPort() > 65535) {
                throw new IllegalArgumentException("本地端口必须在1-65535之间");
            }
            
            if ("tcp".equals(proxy.getType()) || "udp".equals(proxy.getType())) {
                if (proxy.getRemotePort() <= 0 || proxy.getRemotePort() > 65535) {
                    throw new IllegalArgumentException("远程端口必须在1-65535之间");
                }
            }
        }
    }
}